package com.cedifie.lendapp.http;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.lib.base.utils.log.LogHelper;

import java.net.InetAddress;

public class HttpHostDns {
    public void getHttpIPAddressAction(@NonNull String httpUrl, HttpHostDnsCallback callback) {
        final String HOST = httpUrl.replaceFirst("^(https?://)", "");
        new Thread(() -> {
            try {
                InetAddress[] addresses = InetAddress.getAllByName(HOST);
                for (InetAddress address : addresses) {
                    String ipAddress = address.getHostAddress();
                    if (!TextUtils.isEmpty(ipAddress)) {
                        Log.d(HttpHostDns.class.getSimpleName(), "lookup: " + ipAddress);
                        new Handler(Looper.getMainLooper()).post(() -> {
                            callback.onResult(ipAddress);
                        });
                        break;
                    }
                }
            } catch (Exception e) {
                LogHelper.e("Failed to resolve hostname: " + HOST + " , " + e.getLocalizedMessage());
                new Handler(Looper.getMainLooper()).post(() -> {
                    callback.onResult(HOST);
                });
            }
        }).start();
    }

    public interface HttpHostDnsCallback {
        public void onResult(String ipAddress);
    }
}
